import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


public class Datei{
	
	//--------------Speichern in Datei-----------------------
	protected String Speichern(String Dateiname, String Inhalt)
	{
		//init out
		BufferedWriter out = null;
		
		//File Erzeugen
		try
		{
			File f1 = new File(Dateiname);
			if(!f1.exists())
			{
				f1.createNewFile();
			}
		}catch(IOException e)
		{
			return "Fail";
		}
		//Schreiben
		try
		{
			out = new BufferedWriter(new FileWriter(Dateiname));
			String [] abc = Inhalt.split("\n");
			
			for(int i=0;i<abc.length;i++)
			{
				out.write(abc[i]);		
				out.newLine();
			}
		}
		catch(IOException e)
		{
			return "Fail";
		}
		finally
		{
			try
			{
				out.flush();
				out.close();
			}
			catch(IOException e)
			{	 
				return "Fail";
			}
	
		}
		return "OK";
	}	
	//--------------Laden aus Datei--------------------------
	protected String Laden(String Dateiname)
	{
		
		InputStream a_fos =null;
		DataInputStream a_oos = null;
		String temp_line = "";
		String temp_return = "";
		
		//Falls Datei nicht vorhanden --> File Erzeugen
		try
		{
			File f1 = new File(Dateiname);
			if(!f1.exists())
			{
				f1.createNewFile();
			}
			else
			{
				
				try
				{
					//Auslesen aus der Datei
					a_fos = new FileInputStream(Dateiname);
					a_oos = new DataInputStream(a_fos);
					BufferedReader d = new BufferedReader(new InputStreamReader(a_oos));
					
					//Einzelen Lines
					while((temp_line = d.readLine()) != null)
					{
						temp_return += temp_line +"\n";//\n fuer Zeilenumbruch
					}
				}
				catch(IOException e )
				{
					return "Fail";
				}
				finally
				{
					try
					{
						a_oos.close();
					}
					catch(IOException e)
					{	 
						return "Fail";
					}
				}
			}
		}catch(IOException e)
		{
			return "Fail";
		}
		
		return temp_return;
	}
	//--------------Backup Erzeugen--------------------------	
	protected String bak(String Datei_new,String Datei)
	{
		//Auslesen 
		String lade = Laden(Datei);
			
		//Date
		DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
		Date current_date = new Date();
		
		//Erzeugen der Datei + Schreiben
		String save = Speichern(Datei_new+dateFormat.format(current_date)+".ser",lade);
		if(!save.equals("OK"))
			return "Fail";
		
		//Rueckgabe
		return "OK";
	}
}
